package net.sevear.chaos.view
{
	import com.douban.utils.Format;
	
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import flashx.textLayout.formats.TextDecoration;
	
	import net.sevear.chaos.vo.RecommendInfo;
	
	import spark.components.HGroup;
	import spark.components.Label;
	
	public class FromChannelView extends HGroup
	{
		private var _lbls:Vector.<Label>;
		private var _firstLbl:Label;
		private var _recommends:Array;
		public function FromChannelView()
		{
			super();
			_lbls = new Vector.<Label>();
			
			_firstLbl = new Label();
			this.addElement(_firstLbl);
		}
		
		public function setChannelName(channelName:String,color:uint = 0x000000):void{
			while(this.numElements>1){
				this.removeElementAt(this.numElements-1);
			}
			
			_firstLbl.setStyle("color",color);
			_firstLbl.text = channelName;
		}
		
		public function setFromLists(recommends:Array):void{
			_firstLbl.setStyle("color",0x000000);
			_firstLbl.text = "From:";
			_recommends = recommends;
			
			var vIdx:int = 0;
			var item:Label;
			var recommendIdx:int=0
			for(;recommendIdx<recommends.length;recommendIdx++){
				if(_lbls.length>recommendIdx){
					item = _lbls[vIdx] as Label;
					vIdx++;
					if(this.numElements<vIdx+1){
						this.addElement(item);
					}
				}else{
					item = new Label();
					_lbls.push(item);
					this.addElement(item);
				}
				
				item.useHandCursor = true;
				item.buttonMode = true;
				item.text = (recommends[recommendIdx] as RecommendInfo).sourceName;
				if((recommends[recommendIdx] as RecommendInfo).source == RecommendInfo.SOURCE_DOUBANSHUO){
					item.text += "@豆瓣说";
				}
				item.toolTip = Format.dateFormt((recommends[recommendIdx] as RecommendInfo).time);
				item.setStyle("color",0x000000);
				item.setStyle("textDecoration",TextDecoration.UNDERLINE);
				item.addEventListener(MouseEvent.CLICK,onClickFromItem);
			}
			
			while(this.numElements>recommendIdx+1){
				this.removeElementAt(this.numElements-1);
			}
		}
		
		private function onClickFromItem(e:MouseEvent):void{
			var item:Label = e.currentTarget as Label;
			var viewIdx:int = this.getElementIndex(item);
			if(viewIdx>0){
				var recommendInfo:RecommendInfo = _recommends[viewIdx-1] as RecommendInfo;
				var url:String = "";
				if(recommendInfo.source == RecommendInfo.SOURCE_CHAOS){
					url = recommendInfo.sourceURL;
				}else if(recommendInfo.source == RecommendInfo.SOURCE_DOUBANSHUO){
					url = "http://shuo.douban.com/#!/"+recommendInfo.sourceAlias+"/status/"+recommendInfo.id;
				}
				navigateToURL(new URLRequest(url),"_blank");
			}
		}
	}
}